package com.tianqu.tms.www.car.controller;

import java.io.File;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsController;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.exception.TransactionException;
import com.tianqu.tms.core.security.TmsUserProfile;
import com.tianqu.tms.core.util.CopyFile;
import com.tianqu.tms.core.util.DateUtil;
import com.tianqu.tms.core.util.ImageUtils;
import com.tianqu.tms.core.util.Registry;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.core.webservice.weichat.api.WeChatMqApi;
import com.tianqu.tms.core.webservice.weichat.api.rpc.CollectCarInfoBo;
import com.tianqu.tms.dto.TmsFragileStickerHistoryDto;
import com.tianqu.tms.dto.TroubleCarInfoDto;
import com.tianqu.tms.entity.Car;
import com.tianqu.tms.entity.MarketCarInfoTemp;
import com.tianqu.tms.entity.MarketCarService;
import com.tianqu.tms.entity.TmsFragileStickerHistory;

/**
 * @author mufeiyu
 * 车辆采集信息匹对 controller
 */
public class CarInformationCollectMatchController extends TmsController{
	private Logger logger = Logger.getLogger(CarInformationCollectMatchController.class);
	@Override
	public void execute(UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		TxController controller = TxController.getTxController();
		
		// 添加事务提交异常捕获
		try {
			controller.begin();
			long carTempId = Long.parseLong((String)uc.getAttribute("id"));
			if("1".equals((String)uc.getAttribute("value"))){
				Car car = Car.getInstance();
				TmsUserProfile profile = uc.getUserProfile();				
				String vin = (String)uc.getAttribute("vin");
				List<Car> list = car.findCarInfoListByVin(vin);			
				if(list.size() > 0){
					MarketCarInfoTemp carTemp = MarketCarInfoTemp.getInstance();
					carTemp = carTemp.findCarTempInfoById(carTempId);
					MarketCarService carService = MarketCarService.getInstance();
					Car carInfo = list.get(0);				
					
					if(carTemp.getTag1Skip() == 2 || carTemp.getTag2Skip() == 2 || StringUtil.isNotBlank(carTemp.getTempLicensePlate())){
						carInfo.setId(carInfo.getId());
						carInfo.setMileage(carTemp.getMileage());
						if(StringUtil.isNotBlank(carTemp.getTempLicensePlate())){								
							carInfo.setTempLicensePlate(carTemp.getTempLicensePlate());
						}
						if(!StringUtil.isNullOrBlank(carTemp.getPhoto1())){								
							carInfo.setPhoto_1(carTemp.getPhoto1());
						}
						if(!StringUtil.isNullOrBlank(carTemp.getPhoto2())){								
							carInfo.setPhoto_2(carTemp.getPhoto2());
						}
						if(!StringUtil.isNullOrBlank(carTemp.getPhoto3())){	
							carInfo.setPhoto_3(carTemp.getPhoto3());
						}
						if(!StringUtil.isNullOrBlank(carTemp.getPhoto4())){							
							carInfo.setPhoto_4(carTemp.getPhoto4());
						}
						if(!StringUtil.isNullOrBlank(carTemp.getPhoto5())){	
							carInfo.setPhoto_5(carTemp.getPhoto5());
						}
						if(!StringUtil.isNullOrBlank(carTemp.getPhoto6())){								
							carInfo.setPhoto_6(carTemp.getPhoto6());
						}
						if(!StringUtil.isNullOrBlank(carTemp.getPhoto7())){	
							carInfo.setPhoto_7(carTemp.getPhoto7());
						}
						if(!StringUtil.isNullOrBlank(carTemp.getPhoto8())){	
							carInfo.setPhoto_8(carTemp.getPhoto8());
						}						
						carInfo.setAttestStatus(carTemp.getAttestStatus());
						carInfo.setUpdateUserId(profile.getUniqueId());
						carInfo.setEntryStatus(4);
						carInfo.setColor(carTemp.getColor());
						//更新库存车辆信息表（tms_market_car_info）
						carInfo.updateCarMatchInfo(carInfo,carTemp.getTag1Skip(),carTemp.getTag2Skip());
					}
					
					//add by huangwei 2、如果库存车辆信息采集表（tms_market_car_info_temp）的车辆检测是否跳过（tag2Skip）为“2：正常”，那么进行如下操作：
					if(carTemp.getTag2Skip() == 2){
						Car marketCarInfo = list.get(0);
						//如果车辆检测状态（attestStatus）的值被修改，并且库存车辆信息采集表（tms_market_car_info_temp）的车辆检测状态（attestStatus）为非“1：未检测、2：放心车“
						if(marketCarInfo.getAttestStatus() != carTemp.getAttestStatus() && carTemp.getAttestStatus()!=1 && carTemp.getAttestStatus()!=2){
							TroubleCarInfoDto troubleInfo = car.getTroubleCarInfobyVin(marketCarInfo.getVin());
							if(troubleInfo == null){
								TroubleCarInfoDto dto = new TroubleCarInfoDto();
								dto.setTroubleType(carInfo.getAttestStatus());
								dto.setVin(carInfo.getVin());
								car.insertTroubleCarInfo(dto);
							}else{
								TroubleCarInfoDto dto = new TroubleCarInfoDto();
								dto.setTroubleType(carInfo.getAttestStatus());
								dto.setVin(carInfo.getVin());
								car.updateTroubleCarInfo(dto);
							}
						}
						//
						if(marketCarInfo.getAttestStatus() != carTemp.getAttestStatus() &&  carTemp.getAttestStatus()==2){
							TroubleCarInfoDto dto = new TroubleCarInfoDto();
							dto.setTroubleType(carInfo.getAttestStatus());
							dto.setVin(carInfo.getVin());
							car.deleteTroubleCarInfo(dto);
						}
						//
						if(StringUtil.isNotBlank(carTemp.getTempLicensePlate())){
							TmsFragileStickerHistory tmsFragileStickerHistory = TmsFragileStickerHistory.getInstance();
							TmsFragileStickerHistoryDto dto = new TmsFragileStickerHistoryDto();
							dto.setIsPay("2");//不收费
							dto.setMemberId(carInfo.getMemberId()+"");
							if(StringUtil.isNullOrBlank(marketCarInfo.getTempLicensePlate())) dto.setPutType("1");//第一次发帖
							else dto.setPutType("2");
							dto.setSerial(carInfo.getSerial());
							dto.setFragileStickerId(carTemp.getTempLicensePlate());
							dto.setInsertUserId(profile.getUniqueId());
							tmsFragileStickerHistory.insert(dto);
						}
					}
					
					if(carTemp.getTag3Skip() == 2){
						carService.setSerial(carInfo.getSerial());						
						carService.setCheckStatus(carTemp.getCheckStatus());					
						if(carTemp.getCheckStatus() == 2){
							carService.setIsValid(2);//有效
							carService.setCheckImgPath(carTemp.getCheckImgPath());
							carService.setCheckUser(carTemp.getInsertUser());
							carService.setCheckTime(carTemp.getInsertTime());
							carService.setCheckValidTime(getAfterMonthTime());
						}else {
							carService.setIsValid(3);//无效
							carService.setCheckImgPath("");
							carService.setCheckUser("");
							carService.setCheckTime(null);
							carService.setCheckValidTime(null);
						}
						//更新库存车辆业务表（tms_market_car_service）
						carService.updateCarServiceInfo(carService);
					}

					if(carTemp.getTag1Skip() == 2 || carTemp.getTag2Skip() == 2){
						//【TMS_web】车辆采集信息同步到tms并匹对成功 =>【TMS_app】同步
						if(!StringUtil.isNullOrBlank(carInfo.getSerial())){
	                        CollectCarInfoBo collectCarInfoBo = new CollectCarInfoBo();
	                        collectCarInfoBo.setSerial(carInfo.getSerial());
	                        if(carTemp.getTag1Skip() == 2){
		                        collectCarInfoBo.setMileage(carInfo.getMileage());
		                        collectCarInfoBo.setPhoto_1(carInfo.getPhoto_1());
		                        collectCarInfoBo.setPhoto_2(carInfo.getPhoto_2());
		                        collectCarInfoBo.setPhoto_3(carInfo.getPhoto_3());
		                        collectCarInfoBo.setPhoto_4(carInfo.getPhoto_4());
		                        collectCarInfoBo.setPhoto_5(carInfo.getPhoto_5());
		                        collectCarInfoBo.setPhoto_6(carInfo.getPhoto_6());
		                        collectCarInfoBo.setPhoto_7(carInfo.getPhoto_7());
		                        collectCarInfoBo.setPhoto_8(carInfo.getPhoto_8());		                        	                        
		                        collectCarInfoBo.setEntryStatus(carInfo.getEntryStatus());
		                        collectCarInfoBo.setColor(carInfo.getColor());
	                        }
	                        if(carTemp.getTag2Skip() == 2){
	                        	collectCarInfoBo.setAttestStatus(carInfo.getAcceptStatus());
	                        }
	                        collectCarInfoBo.setMarketNo(Integer.parseInt(TmsConstants.MARKET_NO));
	
	                        WeChatMqApi.getInstance().call(collectCarInfoBo);
						}
					}
					
					int isMatch = 2;
					carTemp.setId(carTempId);
					carTemp.setSerial(carInfo.getSerial());
					carTemp.setIsMatch(isMatch);
					//更新库存车辆信息采集表（tmsapp_market_car_info_temp）
					carTemp.updateCarMatchInfo(carTemp);
	
				}
			}else if("2".equals((String)uc.getAttribute("value"))){
				MarketCarInfoTemp carTemp = MarketCarInfoTemp.getInstance();
				int isMatch = 3;
				carTemp.updateCarDeleteInfo(carTempId,isMatch);
			}
			controller.commit();
		} catch (Exception e) {
			try {
				controller.rollback();
			} catch (TransactionException e1) {
				throw new TmsException(TmsException.DB_TXCRROR, e1);
			}
			// 系统异常
			if (e instanceof TmsException) {
				throw e;
			}
			throw new TmsException(TmsException.DB_TXCRROR, e);
		}
		
		logger.debug(this.getClass().getName() + "#execute was completed.");		
	}
	private Timestamp getAfterMonthTime() {
		Calendar c = Calendar.getInstance();// 获得一个日历的实例
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = null;
		try {
			date = (Date) sdf.parse(DateUtil.getCurrentTime());// 初始日期
		} catch (Exception e) {

		}
		c.setTime(date);// 设置日历时间
		c.add(Calendar.MONTH, 1);// 加1个月
		Timestamp dateTime = new Timestamp(c.getTime().getTime());
		return dateTime;
	}
	/**
	 * 复制图片路径
	 * 
	 */
	private String getImagePath(String photo){
		String imgpath = "";
		File inFile = null;
		File outFile1 = null;
		// 生成图片
		String img = System.currentTimeMillis() + ".jpg";// 图片名称
		String path = Registry.getConfig(TmsConstants.TMS_WEB_BASE_IMAGE_PATH);
		path = path.replace("/image/", "");
		inFile = new File(path+photo);
		String outFile = ImageUtils.getImageDirectoryPath(Registry.getConfig(TmsConstants.UPLOADTMP_CONTEXT_ROOT_KEY));
		outFile1 = new File(outFile+img);
		boolean result = CopyFile.copy(inFile, outFile1);
		if(result){
			imgpath = ImageUtils.getImageUrl(Registry.getConfig(TmsConstants.UPLOADTMP_CONTEXT_ROOT_KEY)+img);
		}
		return imgpath;
	}
}
